package com.huiminpay.merchant.service.impl;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.service.SmsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: SmsServiceImpl
 * @Package: com.huiminpay.merchant.service.impl
 * @Description:
 * @Author 谢同学
 * @Create 2023/11/16 17:15
 * @Version 1.0
 */
@Service
@Log4j2
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    /**
     * 发送验证码
     *
     * @param phone 客户手机号
     * @return
     */
    @Override
    public String sendSms(String phone) {
        //手机号非空校验
        if (StringUtil.isBlank(phone)) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //手机号合法性校验
        if (!PhoneUtil.isMatches(phone)) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        String url = smsUrl + "/generate?name=sms&effectiveTime=" + effectiveTime;

        HashMap map = new HashMap();
        map.put("mobile", phone);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/json");

        //封装请参数
        HttpEntity<HashMap> httpEntity = new HttpEntity<>(map, httpHeaders);

        // 处理 post请求；参数：请求路径、请求方式、请求携带的数据（数据 头） 相应类型
        Map body = null;
        ResponseEntity<Map> exchange = restTemplate
                .exchange(url, HttpMethod.POST, httpEntity, Map.class);
        try {
            //获取响应
            body = exchange.getBody();
            log.info("获取的结果：{}", body);
        } catch (Exception e) {
            log.info("获取验证码失败！！");
//            throw new RuntimeException(e);
            throw new BusinessException(CommonErrorCode.E_100107); //发送验证码失败
        }
        //先判断 响应体或者 响应体里面的结果是否为空
        if (body != null || body.get("result") != null) {
            Map<String, String> result = (Map) body.get("result");
            String key = result.get("key");
            log.info("获取的验证码key：{}", key);
            return key;
        } else {
            log.info("验证码获取失败");
//            throw new RuntimeException("验证码获取失败");
            throw new BusinessException(CommonErrorCode.E_100107);
        }

    }

    /**
     * 校验验证码，抛出异常则校验无效
     *
     * @param verifiyKey  验证码key
     * @param verifiyCode 验证码
     */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) {
        //验证码要和手机号进行绑定

        String url = smsUrl + "/verify?name=sms&verificationCode=" + verifiyCode
                + "&verificationKey=" + verifiyKey;
        Map body = null;
        try {
            ResponseEntity<Map> responseEntity = restTemplate
                    .exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            //获取响应
            body = responseEntity.getBody();
            log.info("获取的结果：{}", body);
        } catch (RestClientException e) {
//            throw new RuntimeException(e);
            throw new BusinessException(CommonErrorCode.E_100102);

        }
        if (body == null || !(Boolean) body.get("result")) {
            log.info("验证码有误");
//            throw new RuntimeException("验证码有误");
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }
}
